    let currentPage = 0;
    let totalPages = 0;
    let currentSearchName = ''; // 用于保存当前查询的教师姓名
    let isEditing = false; // 标记是否处于编辑模式
    let originalData = {}; // 用于保存原始数据

    function loadTeachers(page, size, name) {
    console.log("Loading teachers for page:", page, "size:", size, "name:", name);
    let url = "/api/teacher/list";
    if (name) {
    url = "/api/teacher/findByNameLike";
    currentSearchName = name; // 保存当前查询的教师姓名
}

    $.ajax({
    url: url,
    data: {page: page, size: size, name: name},
    method: 'GET'
}).done(function(data) {
    console.log("Data received:", data);
    let html = ``;
    if (data.content.length > 0) {
    data.content.forEach((element, index) => {
    html += `<tr data-id="${element.id}">`;
    html += `<td class="editable">${element.id}</td>`;
    html += `<td class="editable">${element.number}</td>`;
    html += `<td class="editable">${element.name}</td>`;
        if(element.sex==1)
        {
            html += `<td class="editable">男</td>`;
        }else{
            html += `<td class="editable">女</td>`;
        }

    html += `<td class="editable">${element.age}</td>`;
    html += `<td><a href="javascript:void(0)" class="delete-btn" data-id="${element.id}">删除</a></td>`;
    html += "</tr>";
    originalData[element.id] = {
    number: element.number,
    name: element.name,
    sex: element.sex,
    age: element.age
};
});
    currentPage = data.number;
    totalPages = data.totalPages;
    renderPagination();
} else {
    html += "<tr><td colspan='6'>没有找到该教师</td></tr>";
}
    $("#teacherTb").html(html);

    // 绑定删除按钮的点击事件
    $(".delete-btn").click(function() {
    let id = $(this).data("id");
    deleteTeacher(id);
});

    // 绑定编辑按钮的点击事件
    $("#editBtn").click(function() {
    toggleEditMode();
});
}).fail(function() {
    console.error("Failed to load teachers");
    $("#teacherTb").html("<tr><td colspan='6'>查询失败</td></tr>");
});
}

    function renderPagination() {
    console.log("Rendering pagination. Current page:", currentPage, "Total pages:", totalPages);
    let paginationHtml = ``;
    if (totalPages > 1) {
    paginationHtml += `<a href="javascript:void(0)" onclick="loadTeachers(${0}, 12, '${currentSearchName}')" class="layui-laypage-first">首页</a>`;
    for (let i = 0; i < totalPages; i++) {
    paginationHtml += `<a href="javascript:void(0)" onclick="loadTeachers(${i}, 12, '${currentSearchName}')" class="${i == currentPage ? 'layui-laypage-curr' : ''}">${i + 1}</a>`;
}
    paginationHtml += `<a href="javascript:void(0)" onclick="loadTeachers(${totalPages - 1}, 12, '${currentSearchName}')" class="layui-laypage-last">尾页</a>`;
}
    $("#pagination").html(paginationHtml);
}
layui.use(function() {
        var dropdown = layui.dropdown;
        // 渲染
        dropdown.render({
            elem: '.demo-dropdown-base', // 绑定元素选择器，此处指向 class 可同时绑定多个元素
            data: [{
                title: '姓名',
                id: 100
            }, {
                title: '性别',
                id: 101
            }, {
                title: '学工号',
                id: 102
            }],
            click: function (obj) {
                this.elem.find('span').text(obj.title);
            }
        });
    });
    function deleteTeacher(id) {
    console.log("Deleting teacher with id:", id);
    $.ajax({
    url: "/api/teacher/delete",
    data: {id: id},
    method: 'DELETE'
}).done(function() {
    console.log("Teacher deleted successfully");
    loadTeachers(currentPage, 12, currentSearchName); // 刷新当前页面
}).fail(function() {
    console.error("Failed to delete teacher");
    alert("删除失败");
});
}

    function toggleEditMode() {
    isEditing = !isEditing; // 切换编辑模式
    console.log("Toggle edit mode. isEditing:", isEditing); // 添加调试信息

    if (isEditing) {
    $("#editBtn").text("完成"); // 切换到编辑模式时，按钮文本改为“完成”
    $("#teacherTb tr").find(".editable").attr("contenteditable", true);
    $("#teacherTb tr").find(".delete-btn").hide();
} else {
    $("#editBtn").text("编辑"); // 切换回正常模式时，按钮文本改为“编辑”
    $("#teacherTb tr").find(".editable").attr("contenteditable", false);
    $("#teacherTb tr").find(".delete-btn").show();
    console.log("Calling saveEditedTeachers. isEditing:", isEditing); // 添加调试信息
    saveEditedTeachers();
}
}

    function saveEditedTeachers() {
    console.log("Saving edited teachers. isEditing:", isEditing); // 添加调试信息
    $("#teacherTb tr").each(function() {
    let id = $(this).data("id");
    if (id) {
    let teacher = {
    id: id,
    number: $(this).find("td:eq(1)").text().trim(),
    name: $(this).find("td:eq(2)").text().trim(),
    sex: $(this).find("td:eq(3)").text().trim(),
    age: $(this).find("td:eq(4)").text().trim()
};

    console.log("Teacher data to save:", teacher); // 添加调试信息
    updateTeacher(teacher);
}
});
}

    function updateTeacher(teacher) {
    console.log("Updating teacher:", teacher); // 添加调试信息
    $.ajax({
    url: "/api/teacher/update",
    data: JSON.stringify(teacher), // 将对象转换为 JSON 字符串
    method: 'PUT',
    contentType: 'application/json', // 设置 Content-Type
    processData: false // 防止 jQuery 自动转换数据
}).done(function() {
    console.log("Teacher updated successfully");
}).fail(function() {
    console.error("Failed to update teacher");
    alert("保存失败");
});
}

$(function() {
    // 加载所有教师
    loadTeachers(0, 12, '');

    // 查询
    $("#searchBtn").click(function() {
    let name = $("#teacherName").val();
    if (name) {
    name += '%';
    loadTeachers(0, 12, name);
    $("#backbtn").show();
} else {
    loadTeachers(0, 12, '');
}
});

    // 返回
    $("#backbtn").click(function() {
    // 清除输入框中的原有信息
    $("#teacherName").val('');
    currentSearchName = '';
    $("#backbtn").hide();
    // 加载所有教师信息
    loadTeachers(0, 12, '');
});

    // 初始化时隐藏返回按钮
    $("#backbtn").hide();
});

    // 初始化表单验证
layui.use(function (){
    layui.form.on('submit(teacher-dlg)',function () {
        event.preventDefault();//阻止表单默认提交
        commitTeacherGlg();
    })
})
    function showTeacherDlg(){
    layer.open({
        type: 1,
        title: "新增",
        area: ['520px', 'auto'],
        content: $("#addTeacherForm")
    });
}

function commitTeacherGlg(){
    let form = $("#addTeacherForm").serialize();
    $.ajax({
    url: "/api/teacher/add",
    method: "POST",
    data: form,
}).done(result => {
    console.log(result);
    if (result.id) {
    console.log("add success!");
    // 关闭弹窗
    layer.closeAll();
    // 刷新教师列表
    loadTeachers(0, 12, '');
}
}).fail((jqXHR, textStatus, errorThrown) => {
    console.error("Requst failed: " + textStatus + " - " + errorThrown);
    alert("Please try again");
});
    // $("#subBtn").prop("disabled", true) // 禁用按钮
}
